<?php
namespace app\admin\controller\system;
use app\common\annotation\NodeAnnotation;
use app\common\controller\Admin;
use app\common\traits\ControllerCurd;
use Curl\CurlHttpRequest;
use think\helper\Time;
use think\Request;
/**
 * @package app\admin\controller\system
 * @NodeAnnotation(
 *     title="统计管理",
 *     is_menu=0,
 *     is_view=0
 * )
 */
class Tongji extends Admin
{
    /**
     * @NodeAnnotation(
     *     title="百度统计",
     *     parent="admin/system.tongji",
     *     MenuRoot="admin/system.setting"
     * )
     */
    public function index(Request $request)
    {
        $setting = get_option("baidutongji_setting");
        if ($request->isPost())
        {
            $uploadSetting = $this->request->post();
            set_option('baidutongji_setting', $uploadSetting);
            $this->success('设置成功！');
        }
        $this->assign([
            "setting" => $setting
        ]);
        return $this->fetch();
    }
    /**
     * @NodeAnnotation(
     *     title="网站概况",
     *     parent="admin/system.tongji",
     *     MenuRoot="admin/system.setting",
     *     is_menu=0
     * )
     */
    public function siteinfo(Request $request)
    {
        list($todayStart,$todayEnd) = Time::today();
        list($yesTodayStart,$yesTodayEnd) = Time::yesterday();

        $setting = get_option("baidutongji_setting");
        if($setting['type']==1)
        {
            $this->error("暂时只支持百度商业账号接入",url("admin/system.tongji/index"));
        }

        $param = json_encode([
            "header" =>$setting,
            "body" => [
                "site_id" => $setting['site_id'],
                "start_date" => date('Ymd',$yesTodayStart),
                "end_date" => date('Ymd',$todayEnd),
                "metrics" => "pv_count,visitor_count,ip_count,bounce_ratio,avg_visit_time,trans_count, ",
                "method" => "overview/getTimeTrendRpt",
            ]
        ]);

        $tongji = json_decode((new CurlHttpRequest())->curlHttpPost('https://api.baidu.com/json/tongji/v1/ReportService/getData',$param,[
            CURLOPT_HTTPHEADER=>[
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($param)
            ],
        ]),true);

        //halt(json_decode($tongji,true));
        $this->assign([
            "tongji" => $tongji
        ]);
        return $this->fetch();
    }



}